import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'

import { deepCopy } from 'share/common';

import { Form, Button, Icon, message, Collapse, Row, Col, Badge, Popconfirm, Alert, Spin } from 'antd';
const Panel = Collapse.Panel;

import agencyService from 'containers/setting/agency-setting/agency-setting.service'
import AgencyRelationForm from 'containers/setting/agency-setting/agency-relation-form'
import 'styles/setting/agency-setting/agency-relation.scss'

import moment from 'moment';

class AgencyRelation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      uuid: 0,
      billProxyRuleDTOs: [],
      principalInfo: {},
    }
  }

  componentWillReceiveProps(nextProps){
    !this.state.principalInfo.principalOID && this.setState({
      billProxyRuleDTOs: nextProps.billProxyRuleDTOs,
      principalInfo: nextProps.principalInfo,
    })
  }

  //添加代理关系
  add = () => {
    this.setState({ uuid: ++this.state.uuid },() => {
      const keys = this.props.form.getFieldValue('keys');
      let edit_tag = false;
      this.state.billProxyRuleDTOs.map(item => {
        if (item.isEdit || keys.length > 0) edit_tag = true
      });
      if(edit_tag) {
        message.warning(messages('setting.key21'/*你有一个编辑中的代理关系未保存*/));
        return
      }
      const nextKeys = keys.concat(this.state.uuid);
      this.props.form.setFieldsValue({ keys: nextKeys })
    })
  };

  //移除通过 add() 添加的代理关系
  remove = (k) => {
    const { form } = this.props;
    const keys = form.getFieldValue('keys');
    form.setFieldsValue({
      keys: keys.filter(key => key !== k),
    });
  };

  //保存某个代理关系
  handleSave = (principalInfo, key) => {
    this.setState({
      billProxyRuleDTOs: principalInfo.billProxyRuleDTOs,
      principalInfo: principalInfo
    });
    key && this.remove(key)
  };

  //删除某个代理关系
  handleDelete = (index) => {
    let billProxyRuleDTOs = this.state.billProxyRuleDTOs;
    let principalInfo = this.state.principalInfo;
    billProxyRuleDTOs = billProxyRuleDTOs.slice(0, index).concat(billProxyRuleDTOs.slice(index+1));
    principalInfo.billProxyRuleDTOs = billProxyRuleDTOs;
    this.setState({ loading: true });
    agencyService.newAgency(principalInfo).then(res => {
      this.handleSave(res.data);
      message.success(messages('common.operate.success'));
      this.setState({ loading: false })
    }).catch(e => {
      this.setState({ loading: false });
      message.error(`${messages('common.operate.filed')}, ${e.response.data.message}`)
    })
  };

  //编辑某个代理关系
  handleEdit = (e, index, isEdit) => {
    e.stopPropagation();
    let billProxyRuleDTOs = this.state.billProxyRuleDTOs;
    let edit_tag = false;
    isEdit && billProxyRuleDTOs.map(item => {
      if(item.isEdit) {
        edit_tag = true;
      }
    });
    if(edit_tag || this.props.form.getFieldValue('keys').length > 0) {
      message.warning(messages('setting.key21'/*你有一个编辑中的代理关系未保存*/));
      return
    }
    billProxyRuleDTOs[index].isEdit = isEdit;
    this.setState({ billProxyRuleDTOs})
  };

  render(){
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { loading, billProxyRuleDTOs, principalInfo } = this.state;

    getFieldDecorator('keys',  { initialValue: [] });
    const keys = getFieldValue('keys');
    const forms = keys.map(key => {
      return <AgencyRelationForm key={key}
                                 newKey={key}
                                 tab={this.props.tab}
                                 tabKey={this.props.tabKey}
                                 principalInfo={principalInfo}
                                 cancelHandle={() => this.remove(key)}
                                 submitHandle={this.handleSave}/>
    });
    const agencyInfo = billProxyRuleDTOs.map((item, index) => {
      const panelHeader = (
        <div>
          <span className="header-principal">{messages('setting.key13'/*代理人*/)}：{item.proxyName} - {item.emplyeeId}</span>
          <span className="header-principal" style={{marginLeft: 70}}>{messages('setting.key14'/*代理日期*/)}：
            {moment(item.startDate).format("YYYY-MM-DD")}
            {messages('setting.key22'/*至*/)}
            {item.proxyTimeRange === 102 ? moment(item.endDate).format("YYYY-MM-DD") : messages('setting.key16'/*无限制*/)}
          </span>
          <span className="header-principal" style={{marginLeft: 70}}>{messages('common.column.status')}：
            <Badge status={item.enabled ? 'success': 'error'}
                   text={item.enabled ? messages('common.valid') : messages('common.invalid')} />
          </span>
          <span className="header-more">
            <a onClick={(e) => {this.handleEdit(e, index, true)}}>{messages('common.edit')}</a>
            <span className="ant-divider"/>
            <Popconfirm placement="topRight" onConfirm={() => {this.handleDelete(index)}} onClick={e => e.stopPropagation()}
                        title={messages('setting.key23'/*你确定要删除这条数据吗?*/)}
                        overlayStyle={{minWidth: 220}}>
              <a>{messages('common.delete')}</a>
            </Popconfirm>
          </span>
        </div>
      );
      let alertEndDateMessage;
      let alertLeavingDateMessage;
      const endDate = new Date(new Date(item.endDate).getTime() + 86400000);
      let leaveDate = moment(item.leavingDate).format("YYYY-MM-DD");
      if(item.proxyTimeRange === 102 && endDate < new Date()) {
        item.enabled = false;
        alertEndDateMessage = (
          <Alert message={messages('setting.key1437',{arg1: moment(endDate).format("YYYY-MM-DD")}/*该代理关系在 {arg1}日 失效*/)}
                 type="warning" showIcon
                 style={{marginTop:'3px'}} />)
      }
      if(item.status === 1002) {
        alertLeavingDateMessage = (
          <Alert message={messages('setting.key1436',{arg1: item.proxyName,arg2: item.emplyeeId,arg3: leaveDate}/*员工 {arg1}-{arg2} 将于 {arg3} 日离职*/) +
                          `${this.props.tab === 'apply' ?
                            messages('setting.key11'/*，代理关系将于该日期内自动禁用*/) : ''}`}
                 type="warning"
                 showIcon
                 className="warning-alert"/>)
      }
      if(item.status === 1003) {
        item.enabled = false;
        alertLeavingDateMessage = (
          <Alert message={messages('setting.key1435',{arg1: item.proxyName,arg2: item.emplyeeId,arg3: leaveDate}/*员工 {arg1}-{arg2} 已于 {arg3} 日离职*/) +
                          `${this.props.tab === 'apply' ?
                            messages('setting.key10'/*，代理关系已于该日期内自动禁用*/) : ''}`}

                 type="warning"
                 showIcon
                 className="warning-alert"/>)
      }
      let chosenExpense = [];
      let chosenRequest = [];
      let chosenLoan = [];
      item.customFormDTOs.map(bill => {
        bill.formName = bill.valid ? bill.formName : `${bill.formName}${messages('setting.key24'/*已停用*/)}`;
        if (bill.entityType === 1002) {  //报销单
          chosenExpense.push(bill);
        } else if (bill.entityType === 1001) {  //申请单
          chosenRequest.push(bill);
        } else if (bill.entityType === 3001) {  //借款单
          chosenLoan.push(bill);
        }
      });
      const panelItem = (
        <div key={index}>
          <Collapse bordered={false} key={index}>
            <Panel header={panelHeader} className="custom-panel">
              <div>
                <Row style={{marginBottom:'10px'}}>
                  <Col span={2} className="agency-bills-col">{messages('setting.key18'/*代理单据*/)}：</Col>
                  {item.proxyFormScope === 1001 && (
                    <Col span={11} className="agency-bills-col">
                      {messages('common.all'/*全部*/)}
                    </Col>
                  )}
                  {item.proxyFormScope === 1002 && (
                    <Col span={11} className="agency-bills-col">
                      {messages('setting.key19'/*报销单*/)}：{messages("common.total.selected" , { total: chosenExpense.length })}
                    </Col>
                  )}
                  {item.proxyFormScope === 1002 && (
                    <Col span={11} className="agency-bills-col">
                      {messages('setting.key20'/*申请单*/)}：{messages("common.total.selected" , { total: chosenRequest.length })}
                    </Col>
                  )}
                </Row>
                {item.proxyFormScope === 1002 && (
                  <Row style={{marginBottom:'10px'}}>
                    <Col span={11} offset={2} className="agency-bills-col"> {messages('setting.key1742')/*借款单*/}：{messages("common.total.selected" , { total: chosenLoan.length })}
                    </Col>
                  </Row>
                )}
              </div>
            </Panel>
          </Collapse>
          {alertEndDateMessage}
          {alertLeavingDateMessage}
        </div>
      );
      const editItem = <AgencyRelationForm key={index}
                                           tab={this.props.tab}
                                           tabKey={this.props.tabKey}
                                           defaultValues={item}
                                           principalInfo={principalInfo}
                                           cancelHandle={e => this.handleEdit(e, index, false)}
                                           submitHandle={this.handleSave}/>;
      return item.isEdit ? editItem : panelItem
    });
    return (
      <div className="agency-relation">
        <h3 className="header-title">{messages('setting.key25'/*代理关系*/)}</h3>
        {this.props.tab !== 'behalfOthers' && <p className="header-info">
          {this.props.tab === 'apply' ?
            messages('setting.key26'/*选择哪些员工可以帮被代理人提交单据*/) :
            messages('setting.key27'/*选择哪些员工可以帮被代理人审批单据*/)}
          <span className="ant-divider"/>
          {messages('setting.key28'/*选择哪些员工可以帮代理人提交单据*/)}
        </p>}
        <Spin spinning={loading}>{agencyInfo}</Spin>
        {forms}
        <Button type="dashed" className="new-relation-btn" onClick={this.add}>
          <Icon type="plus" /> {messages('common.add')}
        </Button>
      </div>
    )
  }

}

function mapStateToProps() {
  return {}
}

const WrappedAgencyRelation = Form.create()(AgencyRelation);

export default connect(mapStateToProps)(WrappedAgencyRelation);
